package github.liweiwei.sort;

import java.util.Arrays;

/**
 * @Author: DRevelation
 * @Date: 2021/9/16 17:41
 */
public class MergeSort {
    public static void main(String[] args) {
        int[] arr = {5, 2, 4, 1, 3};
        System.out.println("======排序前arr: " + Arrays.toString(arr));
        mergeSort(arr, 0, arr.length - 1);
        System.out.println("======排序后arr: " + Arrays.toString(arr));
    }

    private static void mergeSort(int[] arr, int left, int right) {
        if (left >= right) {
            return;
        }
        //避免过大发生溢出 相当于(right+left)/2
        int mid = left + (right - left) / 2;
        mergeSort(arr, left, mid);
        mergeSort(arr, mid + 1, right);
        merge(arr, left, mid, right);
    }


    private static void merge(int[] arr, int left, int mid, int right) {
        int length = right - left + 1;
        int[] temp = new int[length];
        for (int i = 0; i < length; i++) {
            temp[i] = arr[left + i];
        }
        //左边数组起始位置
        int l = 0;
        //右边数组起始位置
        int r = mid - left + 1;
        for (int i = 0; i < length; i++) {
            if (l > mid - left) {
                arr[i + left] = temp[r];
                r++;
            } else if (r > length - 1) {
                arr[i + left] = temp[l];
                l++;
            } else if (temp[l] < temp[r]) {
                arr[i + left] = temp[l];
                l++;
            } else {
                arr[i + left] = temp[r];
                r++;
            }
        }
    }

}
